package com.lvan.rabbit.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Lvan
 */
public class RabbitMQUtil {

    private static ConnectionFactory connectionFactory;

    static {
        // 创建连接mq的连接工厂
        connectionFactory = new ConnectionFactory();
        // 设置连接rabbitmq主机
        connectionFactory.setHost("192.168.1.108");
        connectionFactory.setPort(5672);
        // 设置连接那个虚拟主机
        connectionFactory.setVirtualHost("/ems");
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("ems");
    }

    /**
     * 获取连接对象
     */
    public static Connection getConnection() {
        try {
            return connectionFactory.newConnection();
        } catch (IOException | TimeoutException e) {
            return null;
        }
    }

    /**
     * 关闭 通道 及 连接
     */
    public static void closeConnectionAndChanel(Channel channel, Connection connection) {
        try {
            if (channel != null) { channel.close();  }
            if (connection != null) { connection.close(); }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
